from flask import Flask, request, jsonify
import pymysql

app = Flask(__name__)

# 配置数据库连接（替换为你的实际信息）
DB_CONFIG = {
    'host': '127.0.0.1',
    'user': 'root',
    'password': 'hsp',
    'database': 'tcp_data_db',
    'port': 3306
}
@app.route('/api/data', methods=['GET'])
def query_data():
    # 获取请求参数（时间格式需与数据库一致，如：2025-07-26 11:05:00）
    start = request.args.get('start_time')
    end = request.args.get('end_time')

    # 校验参数
    if not (start and end):
        return jsonify({"error": "缺少 start_time 或 end_time 参数"}), 400

    try:
        # 连接数据库并查询
        conn = pymysql.connect(**DB_CONFIG)
        with conn.cursor(pymysql.cursors.DictCursor) as cursor:
            sql = "SELECT * FROM tcp_data WHERE timestamp BETWEEN %s AND %s"
            cursor.execute(sql, (start, end))
            result = cursor.fetchall()
        conn.close()

        return jsonify(result)  # 返回 JSON 格式结果
    except Exception as e:
        return jsonify({"error": str(e)}), 500

if __name__ == '__main__':
    app.run(debug=True, port=5000)  # 启动服务，默认端口 5000